//
//  RunAllResultsViewController.m
//  GCDBenchmark
//
//  Created by Codex on 2025/10/30.
//

#import "RunAllResultsViewController.h"

@interface RunAllResultsViewController ()
@property (nonatomic, strong) UIView *containerView;
@property (nonatomic, strong) UILabel *titleLabel;
@property (nonatomic, strong) UILabel *statusLabel;
@property (nonatomic, strong) UITextView *logTextView;
@property (nonatomic, strong) UIButton *closeButton;
@property (nonatomic, assign) NSInteger totalCount;
@property (nonatomic, assign) NSInteger completedCount;
@property (nonatomic, assign) BOOL batchFinished;
@end

@implementation RunAllResultsViewController

- (void)viewDidLoad {
    [super viewDidLoad];
    [self setupUI];
    [self animateIn];
}

- (void)setupUI {
    self.view.backgroundColor = [[UIColor blackColor] colorWithAlphaComponent:0.35];

    self.containerView = [[UIView alloc] init];
    self.containerView.backgroundColor = [UIColor systemBackgroundColor];
    self.containerView.layer.cornerRadius = 18;
    self.containerView.translatesAutoresizingMaskIntoConstraints = NO;
    [self.view addSubview:self.containerView];

    UIView *handleView = [[UIView alloc] init];
    handleView.backgroundColor = [UIColor tertiaryLabelColor];
    handleView.layer.cornerRadius = 3;
    handleView.translatesAutoresizingMaskIntoConstraints = NO;
    [self.containerView addSubview:handleView];

    self.titleLabel = [[UILabel alloc] init];
    self.titleLabel.font = [UIFont systemFontOfSize:20 weight:UIFontWeightSemibold];
    self.titleLabel.text = @"全部测试执行";
    self.titleLabel.translatesAutoresizingMaskIntoConstraints = NO;
    [self.containerView addSubview:self.titleLabel];

    self.closeButton = [UIButton buttonWithType:UIButtonTypeSystem];
    [self.closeButton setTitle:@"完成" forState:UIControlStateNormal];
    self.closeButton.titleLabel.font = [UIFont systemFontOfSize:16 weight:UIFontWeightSemibold];
    [self.closeButton addTarget:self action:@selector(closeButtonTapped:) forControlEvents:UIControlEventTouchUpInside];
    self.closeButton.translatesAutoresizingMaskIntoConstraints = NO;
    self.closeButton.enabled = NO;
    self.closeButton.alpha = 0.4;
    [self.containerView addSubview:self.closeButton];

    self.statusLabel = [[UILabel alloc] init];
    self.statusLabel.font = [UIFont systemFontOfSize:14];
    self.statusLabel.textColor = [UIColor secondaryLabelColor];
    self.statusLabel.numberOfLines = 0;
    self.statusLabel.text = @"准备开始执行...";
    self.statusLabel.translatesAutoresizingMaskIntoConstraints = NO;
    [self.containerView addSubview:self.statusLabel];

    self.logTextView = [[UITextView alloc] init];
    self.logTextView.backgroundColor = [UIColor secondarySystemBackgroundColor];
    self.logTextView.layer.cornerRadius = 10;
    self.logTextView.font = [UIFont monospacedSystemFontOfSize:13 weight:UIFontWeightRegular];
    self.logTextView.textColor = [UIColor labelColor];
    self.logTextView.editable = NO;
    self.logTextView.alwaysBounceVertical = YES;
    self.logTextView.textContainerInset = UIEdgeInsetsMake(12, 12, 12, 12);
    self.logTextView.translatesAutoresizingMaskIntoConstraints = NO;
    [self.containerView addSubview:self.logTextView];

    [NSLayoutConstraint activateConstraints:@[
        [self.containerView.leadingAnchor constraintEqualToAnchor:self.view.leadingAnchor constant:12],
        [self.containerView.trailingAnchor constraintEqualToAnchor:self.view.trailingAnchor constant:-12],
        [self.containerView.bottomAnchor constraintEqualToAnchor:self.view.safeAreaLayoutGuide.bottomAnchor constant:-12],
        [self.containerView.heightAnchor constraintEqualToConstant:420],

        [handleView.topAnchor constraintEqualToAnchor:self.containerView.topAnchor constant:10],
        [handleView.centerXAnchor constraintEqualToAnchor:self.containerView.centerXAnchor],
        [handleView.widthAnchor constraintEqualToConstant:44],
        [handleView.heightAnchor constraintEqualToConstant:6],

        [self.titleLabel.topAnchor constraintEqualToAnchor:handleView.bottomAnchor constant:12],
        [self.titleLabel.leadingAnchor constraintEqualToAnchor:self.containerView.leadingAnchor constant:18],
        [self.titleLabel.trailingAnchor constraintLessThanOrEqualToAnchor:self.closeButton.leadingAnchor constant:-12],

        [self.closeButton.centerYAnchor constraintEqualToAnchor:self.titleLabel.centerYAnchor],
        [self.closeButton.trailingAnchor constraintEqualToAnchor:self.containerView.trailingAnchor constant:-18],
        [self.closeButton.widthAnchor constraintGreaterThanOrEqualToConstant:60],
        [self.closeButton.heightAnchor constraintEqualToConstant:32],

        [self.statusLabel.topAnchor constraintEqualToAnchor:self.titleLabel.bottomAnchor constant:8],
        [self.statusLabel.leadingAnchor constraintEqualToAnchor:self.containerView.leadingAnchor constant:18],
        [self.statusLabel.trailingAnchor constraintEqualToAnchor:self.containerView.trailingAnchor constant:-18],

        [self.logTextView.topAnchor constraintEqualToAnchor:self.statusLabel.bottomAnchor constant:12],
        [self.logTextView.leadingAnchor constraintEqualToAnchor:self.containerView.leadingAnchor constant:18],
        [self.logTextView.trailingAnchor constraintEqualToAnchor:self.containerView.trailingAnchor constant:-18],
        [self.logTextView.bottomAnchor constraintEqualToAnchor:self.containerView.bottomAnchor constant:-18],
    ]];
}

- (void)animateIn {
    self.containerView.transform = CGAffineTransformMakeTranslation(0, 420);
    self.view.alpha = 0;
    [UIView animateWithDuration:0.28 delay:0 options:UIViewAnimationOptionCurveEaseOut animations:^{
        self.containerView.transform = CGAffineTransformIdentity;
        self.view.alpha = 1;
    } completion:nil];
}

- (void)animateOut:(void (^)(void))completion {
    [UIView animateWithDuration:0.22 delay:0 options:UIViewAnimationOptionCurveEaseIn animations:^{
        self.containerView.transform = CGAffineTransformMakeTranslation(0, 420);
        self.view.alpha = 0;
    } completion:^(BOOL finished) {
        if (completion) {
            completion();
        }
    }];
}

- (void)closeButtonTapped:(UIButton *)sender {
    if (!self.batchFinished) {
        return;
    }
    [self animateOut:^{
        [self dismissViewControllerAnimated:NO completion:^{
            if (self.onClose) {
                self.onClose();
            }
        }];
    }];
}

- (void)prepareWithTotalCount:(NSInteger)count {
    dispatch_async(dispatch_get_main_queue(), ^{
        self.totalCount = count;
        self.completedCount = 0;
        self.batchFinished = NO;
        self.closeButton.enabled = NO;
        self.closeButton.alpha = 0.4;
        self.statusLabel.text = [NSString stringWithFormat:@"共 %ld 个测试等待执行", (long)count];
        self.logTextView.text = @"";
    });
}

- (void)updateStatus:(NSString *)status {
    dispatch_async(dispatch_get_main_queue(), ^{
        self.statusLabel.text = status;
    });
}

- (void)appendLog:(NSString *)log {
    dispatch_async(dispatch_get_main_queue(), ^{
        if (self.logTextView.text.length == 0) {
            self.logTextView.text = log;
        } else {
            self.logTextView.text = [self.logTextView.text stringByAppendingFormat:@"\n\n%@", log];
        }
        NSRange bottom = NSMakeRange(self.logTextView.text.length - 1, 1);
        [self.logTextView scrollRangeToVisible:bottom];
    });
}

- (void)updateCountdown:(NSInteger)seconds nextTestName:(nullable NSString *)name {
    dispatch_async(dispatch_get_main_queue(), ^{
        if (seconds <= 0) {
            self.statusLabel.text = @"准备开始下一个测试...";
            return;
        }
        NSString *displayName = name ?: @"下一项";
        self.statusLabel.text = [NSString stringWithFormat:@"😴 %@将在 %ld 秒后开始", displayName, (long)seconds];
    });
}

- (void)markBatchCompletedWithSummary:(NSString *)summary autoExit:(BOOL)autoExitEnabled {
    dispatch_async(dispatch_get_main_queue(), ^{
        self.batchFinished = YES;
        self.completedCount = self.totalCount;
        self.statusLabel.text = summary;
        self.closeButton.enabled = YES;
        self.closeButton.alpha = 1.0;
        if (autoExitEnabled) {
            [self appendLog:@"⚠️ 配置启用自动退出，将在窗口关闭后退出程序。"];
        } else {
            [self appendLog:@"✅ 全部测试执行完毕。"];
        }
    });
}

@end
